package com.tools.scanner.ui.dialog

import android.content.Context
import android.os.Bundle
import android.text.TextUtils
import android.view.View
import android.view.WindowManager
import android.widget.EditText
import android.widget.TextView
import androidx.appcompat.app.AlertDialog
import com.tools.scanner.R
import com.tools.scanner.utils.ToastUtil
import java.io.File

class InputPdfNameDialog(
    context: Context,
    private val parentFile: File,
    private val fileName: String,
    private val callback: (value: String) -> Unit
) : AlertDialog(context) {

    private var mEditText: EditText? = null
    private var mTvError: TextView? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.dialog_input_pdf_name)
        setCancelable(false)

        mTvError = findViewById(R.id.tv_error)
        mEditText = findViewById(R.id.editText)
        mEditText?.setText(fileName)
        mEditText?.setSelection(fileName.length)

        window?.let {
            it.clearFlags(
                WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
                        or WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM
            )
            it.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE)
        }

        setOnShowListener {
            mEditText?.requestFocus()
        }

        findViewById<View>(R.id.tv_cancel)?.setOnClickListener {
            dismiss()
        }

        findViewById<View>(R.id.tv_save)?.setOnClickListener {
            save()
        }
    }

    private fun save() {
        val value = mEditText?.text.toString()
        if (TextUtils.isEmpty(value)) {
            ToastUtil.showToast(R.string.please_input_file_name)
            return
        }

        if (File(parentFile, value).exists()) {
            mTvError?.visibility = View.VISIBLE
            return
        }

        dismiss()
        callback(value)
    }

}